import axios from "axios"
import qs from "qs"
import util from "@/plugins/util"
import config from "../../config"
import { router } from "@/router"

const IMAGE_PREFIX = window.$globalconfig.UPLOAD.IMAGE_PREFIX.split("?")[0]
const FILE_PREFIX = window.$globalconfig.UPLOAD.FILE_PREFIX.split("?")[0]

const getToken = () => util.auth.getToken();

axios.defaults.baseURL = $globalconfig.URLS.API;
axios.defaults.retry = 5;
axios.defaults.timeout = 10000;
axios.defaults.retryDelay = 5000;

axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    // if (config.url != "api/userlogin/login") {
    //   if (getToken()) {
    //     config.params ? "" : (config.params = {});
    //     config.params.token ? "" : (config.params.token = getToken());
    //     // config.params.t = Date.now(); // 后退防止缓存
    //   } else {
    //     VM.$vgo.throttle(
    //       () => VM.$vgo.tip("登录过期，请重新登录", "warning"),
    //       100
    //     );
    //     return new Promise(() => { });
    //   }
    // }
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  res => {
    // 对响应数据做点什么
    if (!res.config.noLoading) window.VM.$vgo.closeLoading();
    if (res.data.code == 100 || res.data.code == 200) {
      return res.data || res;
    } else if (res.data.msg) {
      VM.$vgo.tip(res.data.msg, "error");
      return Promise.reject(res.data);
    }
  },
  ({ response }) => {
    // 对响应错误做点什么
    // if (response.status === 401) {
    //   let url = window.location.href;
    //   if (process.env.NODE_ENV != "production") {
    //     url = "http://localhost:" + config.dev.port + "/#/";
    //   }
    //   // 跳转登录
    //   window.location.href = `${$globalconfig.URLS.API}user/login?redirect_uri=${encodeURIComponent(url)}`
    //   // router.push({name: 'login'})
    // }

    return Promise.reject(response);
  }
);

const onUploadProgress = (e, num) => {
  window.VM.$vgo.loading.text = `当前上传${num}项(单次上传限制10项), 已上传: ${Math.min(
    ((e.loaded / e.total) * 100).toFixed(0),
    99
  )}%`;
};

const uploadApi = (fileList, action, opts = {}) => {
  const { url = IMAGE_PREFIX, iswaterMark } = opts;
  let formData = new FormData();
  iswaterMark && formData.append("iswaterMark", +iswaterMark);
  formData.append("action", action);
  console.log(fileList)
  if (Array.isArray(fileList)) {
    fileList.map(i => {
      formData.append("file", i.raw);
    });
  } else {
    formData.append("file", fileList.raw);
  }
  window.VM.$vgo.openLoading();
  return axios({
    method: "post",
    "Content-Type": "multipart/form-data",
    url,
    timeout: 0,
    onUploadProgress: e => onUploadProgress(e, fileList.length || 1),
    data: formData
  })
    .then(res => {
      window.VM.$vgo.closeLoading();
      return Promise.resolve(res);
    })
    .catch(err => {
      window.VM.$vgo.closeLoading();
      return Promise.reject(err);
    });
};

export default {
  // 获取主页套餐列表
  getHomeInfo () {
    return axios.get('api/user/functions');
  },
  uploadApi,
  // 获取用户信息
  getUserInfo () {
    return axios.get(`api/user/session?token=${getToken()}`);
  },
  checkPblishPwd (publishpassword) {
    return axios.get(
      `api/user/checkpublishstatus?publishpassword=${publishpassword}`
    );
  },
  // 获取用户未读消息
  getUserUnReadMessage () {
    return axios.get(`api/user/msgs/noseecount`, { noLoading: true });
  },
  // 获取用户认证信息
  getUserCertificateInfo () {
    return axios.get(`api/user/rzcert`);
  },
  // 更新/添加用户认证信息 nature是否摄影师 1否 2是 , rz_status 未填写 = 1,待审核 = 2,审核不通过 = 3,审核通过 = 4
  addOrUpdateUserCertificateInfo (opts) {
    return axios.post(
      `api/user/rzcert`,
      qs.stringify({
        rzcert_id: opts.rzcert_id || "",
        legalman: opts.legalman, //姓名
        tel: opts.tel,
        cardno: opts.cardno,
        cardfronturl: opts.cardfronturl,
        cardbackurl: opts.cardbackurl,
        nature: opts.nature,
        vcode: opts.vcode
      })
    );
  },
  // 用户签到
  checkin () {
    return axios.post(`api/user/checkin`, qs.stringify({}));
  },
  // 用户绑定手机验证码 api/sms/send
  getBindPhoneVerifyCode (mobile) {
    return axios.post(
      `api/sms/send`,
      qs.stringify({
        ischeckexist: false,
        mobile: mobile
      })
    );
  },
  // 用户绑定邮箱验证码
  getBindEmailVerifyCode (email) {
    return axios.post(
      `api/email/send`,
      qs.stringify({
        email: email
      })
    );
  },

  // 用户改密码
  updatePassword (oldpassword, password) {
    return axios.put(
      `api/user/password?oldpassword=${oldpassword}&password=${password}`,
      {}
    );
  },
  // 更新账户绑定信息（1=手机 2=邮箱,4提现帐号）
  upateUserBind (opts) {
    return axios.put(`api/user/account/bind`, {
      type: opts.type,
      vcode: opts.vcode || "",
      email: opts.email || "",
      phone: opts.phone || "",
      bindcardname: opts.bindcardname || "",
      bindcard: opts.bindcard || ""
    });
  },
  // api/frontsite/indexpanos 首页精选全景作品
  getIndexPanoList () {
    return axios.get(`api/frontsite/indexpanos`);
  },
  // api/frontsite/tags 全景分类标签
  // getPanoTags () {
  //   return axios.get(`api/frontsite/tags`);
  // },
  // api/frontsite/hottags?type=0
  getPanoHottags (id) {
    return axios.get(`api/frontsite/hottagandcitys/${id}`);
  },
  // api/frontsite/panos/1/12?keyword=&tag_id=&orderBy=
  // 获取作品数据列表
  getPanoList (opts) {
    return axios.get(`api/frontsite/panos/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        tag_id: opts.tagId,
        keyword: opts.keyword,
        orderBy: opts.orderBy,
        user_id: opts.userId,
        cate_id: opts.cateid,
        is_show_pano: 1,
      },
    });
  },
  // api/frontsite/videos/1/12 VR视频数据
  getVideoList (opts) {
    let data = opts
    if (!opts.trade) {
      data = {
        pageIndex: opts.pageIndex,
        pageSize: opts.pageSize,
      }
    }
    return axios.get(`api/frontsite/videos/${data.pageIndex}/${data.pageSize}`, {
      params: {
        tag_id: data.tagId,
        keyword: data.keyword,
        orderBy: data.orderBy,
        trade: data.trade,
        is_show_video: 1,
      },
    });
  },
  // api/frontsite/rlive/{page}/{pageSize} 直播数据
  getLiveList (opts) {
    return axios.get(`api/frontsite/vrlive/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        tag_id: opts.tagId,
        keyword: opts.keyword,
        orderBy: opts.orderBy,
      },
    });
  },
  // 房地产数据 api/frontsite/vrestate
  getEstateList (opts) {
    return axios.get(`api/frontsite/vrestate/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        tag_id: opts.tagId,
        keyword: opts.keyword,
        orderBy: opts.orderBy,
        is_show_estate: 1,
      },
    });
  },
  // 3D模型数据 api/frontsite/3D
  get3dList (opts) {
    return axios.get(`api/frontsite/3D/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        tag_id: opts.tagId,
        keyword: opts.keyword,
        orderBy: opts.orderBy,
        is_show_3dmodel: 1,
      },
    });
  },
  // 360环物数据 api/frontsite/360objects
  get360List (opts) {
    return axios.get(`api/frontsite/360objects/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        tag_id: opts.tagId,
        keyword: opts.keyword,
        orderBy: opts.orderBy,
        is_show_mat: 1,
      },
    });
  },
  // VR展厅数据 api/frontsite/events
  getEventsList (opts) {
    return axios.get(`api/frontsite/events/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        is_show_event_company: 1,
      }
    });
  },
  // idstr(VR旅游类型（2，0是新旧总览图） 1、手绘图)
  getOverviewsList (opts) {
    return axios.get(`api/frontsite/overviews/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        idstr: '0,2',
        is_show_overview: 1,
      },
    });
  },
  // idstr(VR旅游类型（2，0是新旧总览图） 1、手绘图)
  getHanddrawList (opts) {
    return axios.get(`api/frontsite/overviews/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        idstr: '1',
        is_show_overview: 1,
      },
    });
  },
  // VR行走漫游
  getWalkList (opts) {
    return axios.get(`api/frontsite/download/files/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        cate_id: -1,
        is_show_walking_tour: 1,
      },
    });
  },

  // api/pmarket/types 作品市场分类标签
  getPmarketTags () {
    return axios.get(`api/pmarket/types`);
  },
  // api/frontsite/pmarket/panos/1/12 作品市场列表
  getPmarketList (opts) {
    return axios.get(`api/frontsite/pmarket/panos/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        pano_type: opts.pano_type,
        keyword: opts.keyword,
      },
    });
  },
  // api/frontsite/pmarket/panos/5 作品市场的单个作品详情
  getPmarketDetailData (id) {
    return axios.get(`api/frontsite/pmarket/panos/${id}`);
  },
  // api/frontsite/users/{page}/{pageSize} 作者列表
  getAuthorList (opts) {
    return axios.get(`api/frontsite/users/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        orderBy: opts.orderBy,
        keyword: opts.keyword,
      },
    });
  },
  // api/frontsite/users/{user_id} 作者详情
  getAuthorDetail (id) {
    return axios.get(`api/frontsite/users/${id}`);
  },
  // api/user/panocates?pano_type_id=0&user_id=10002 某作者下的作品页分类标签
  getAuthorPanoTags (opts) {
    return axios.get(`api/frontsite/panocates/${opts.userId}`, {
      params: {
        pano_type_id: opts.panoTypeId,
      },
    });
  },


  // 资讯类型 api/frontsite/newstypes
  getInfoTags () {
    return axios.get(`api/frontsite/newstypes`);
  },

  // api/frontsite/news/1/12?type_id=3&orderBy= 资讯列表
  getInfoList (opts) {
    return axios.get(`api/frontsite/news/${opts.pageIndex}/${opts.pageSize}`, {
      params: {
        orderBy: opts.orderBy,
        type_id: opts.typeId,
      },
    });
  },

  // api/frontsite/news/71 资讯详情
  getInfoDetailData (id) {
    return axios.get(`api/frontsite/news/${id}`);
  },

  // api/frontsite/news/{id} 资讯点赞
  praiseInfoDetail (id) {
    return axios.put(`api/frontsite/news/${id}`);
  },

  // api/pmarket/user/carts 购物车列表
  getCartList () {
    return axios.get(`api/pmarket/user/carts`, {
      params: {
        token: getToken()
      }
    });
  },

  // api/pmarket/user/carts/24 单个删除购物车商品
  // api/pmarket/user/carts/26,27,28 批量删除
  deleteCartProduct (ids) {
    return axios.delete(`api/pmarket/user/carts/${ids}?token=${getToken()}`);
  },

  // api/pmarket/user/carts 加入购物车
  addCartProduct (id) {
    return axios.post(`api/pmarket/user/carts?market_pano_id=${id}&token=${getToken()}`);
  },

  // api/pmarket/user/panoorders 创建订单
  createProductOrder (opts) {
    return axios.post(`api/pmarket/user/panoorders?token=${getToken()}`, {
      email: opts.email,
      pano_cart_ids: opts.ids,
    });
  },

  // api/payorder/create支付 paytype=1支付宝，2微信支付，3余额支付
  // opts = {
  //   ordertype: 9,
  //   paytype: 3,
  //   productid: 7,
  //   return_url: 'https://user.vgoyun.com/#/smart-city/my-order',
  // }
  modePay (opts) {
    return axios.post(`api/payorder/create?token=${getToken()}`, qs.stringify(opts));
  },

  // 登录
  // opts = {
  //   username: '',
  //   password: '',
  //   vcode: '',
  // }
  login (opts) {
    return axios.post(`user/login`, qs.stringify(opts));
  },

  // 发送验证码 api/sms/send
  // opts = {mobile: ''}
  sendVcode (opts) {
    return axios.post(`api/sms/send`, qs.stringify(opts));
  },

  // 获取验证码图片 common/vcode
  getVcodeImage () {
    return axios.get(`common/vcode?_t=${Date.now()}`);
  },

  // 在线预约 api/frontsite/users/panotasks
  // opts = {
  //   contact: "18059770487",
  //   content: "测试数据",
  //   fk_user_id: "10002",
  //   personname: "测试"
  // }
  sendBooking (opts) {
    return axios.post(`api/frontsite/users/panotasks`, opts);
  },

  // 获取全景作品链接 api/frontsite/panoswiperrands/1
  getPanoUrl (type = 0) {
    return axios.get(`api/frontsite/panoswiperrands/1?type=${type}`);
  },

  // 地图 api/frontsite/panomaps
  getPanoMapList: (model) => axios.get(`api/frontsite/panomaps?tag=${model.tag}`),

  /**
   * 获取banners是否为全景图的开关
   * @returns {Promise}
   */
  getBannersSwitch: () => axios.get(`api/frontsite/configs`),

  /**
   * 获取普通图片
   * @param page
   * @param pageSize
   * @param typeId
   * @returns {Promise}
   */
  getBannersPic: (page, pageSize, typeId = 0) => axios.get(`api/zaigou/banners/${page}/${pageSize}?type_id=${typeId}`),

  /**
   * 获取全景图
   * @param count
   * @returns {Promise}
   */
  getBannersVrpic: (count) => axios.get(`api/frontsite/panoswiperrands/${count}`),

  // 官网配置信息
  getSiteconfigs: () => axios.get(`api/front/siteconfigs`),
};
